package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.Service;
import com.google.common.util.concurrent.ServiceManager;

import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 服务管理器示例
 *
 * @author yangyunjiao
 */
public class ServiceManagerExample {
    public static void main(String[] args) {
        // 创建多个服务
        MonitoringService monitoringService = new MonitoringService(2000);
        MessageProcessingService messageService = new MessageProcessingService(100, 10);

        // 创建服务管理器
        ServiceManager serviceManager = new ServiceManager(
                Arrays.asList(monitoringService, messageService)
        );

        // 添加监听器
        serviceManager.addListener(new ServiceManager.Listener() {
            @Override
            public void healthy() {
                System.out.println("所有服务都正常运行");
            }

            @Override
            public void stopped() {
                System.out.println("所有服务都已停止");
            }

            @Override
            public void failure(Service service) {
                System.err.println("服务失败: " + service);
            }
        }, Executors.newSingleThreadExecutor());

        // 启动所有服务
        serviceManager.startAsync().awaitHealthy();

        try {
            // 模拟运行一段时间
            Thread.sleep(3000);

            // 向消息服务添加一些消息
            for (int i = 0; i < 10; i++) {
                messageService.offerMessage(
                        new MessageProcessingService.Message("测试消息 " + i)
                );
            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 优雅停止所有服务
            try {
                serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                System.err.println("服务停止超时");
            }
        }
    }
}
